package br.com.comanda.webservice.dao.impl;

import java.util.List;

import org.hibernate.Query;

import br.com.comanda.webservice.dao.ItemDAO;
import br.com.comanda.webservice.model.Item;

public class ItemDAOImpl extends GenericDAOImpl<Item> implements ItemDAO {

	public ItemDAOImpl() {
		super(Item.class);
	}

	public Item getItemByAccountAndProduct(int accountId, int productId) {

		String hql = "SELECT item FROM Item item where item.account.id = :accountId and item.product.id = :productId";

		Query query = this.getSession().createQuery(hql);

		query.setParameter("productId", productId);
		query.setParameter("accountId", accountId);

		Item item = (Item) query.uniqueResult();
		return item;
	}

	@SuppressWarnings("unchecked")
	public List<Item> findItensByAccount(int accountId) {
		String hql = "SELECT item FROM Item item where item.account.id = :accountId";

		Query query = this.getSession().createQuery(hql);
		query.setParameter("accountId", accountId);

		return query.list();
	}

	public void updateQtdeItem(Item item) {
		String hql = "update Item set quantity = :qtde, total = :total where id = :id";
		Query query = this.getSession().createQuery(hql);
		query.setParameter("id", item.getId());
		query.setParameter("qtde", item.getQuantity());
		query.setParameter("total", item.getTotal());

		this.getSession().beginTransaction().begin();
		query.executeUpdate();
		this.getSession().beginTransaction().commit();
	}

	public void delete(long id) {
		String hql = "delete Item where id = :id";
		Query query = this.getSession().createQuery(hql);
		query.setParameter("id", id);

		this.getSession().beginTransaction().begin();
		query.executeUpdate();
		this.getSession().beginTransaction().commit();
	}

}
